<template>
  <view class="audio-player" @tap="audioPlay">
    <text class="time">{{ time }}</text>
    <view class="controls play-btn">
      <image
        :src="showAnimation ? voiceMsgMyLeft : voiceMsgLeft"
        v-if="direction === 'self'"
      ></image>
      <image
        :src="showAnimation ? voiceMsgMyRight : voiceMsgRight"
        v-if="direction !== 'self'"
      ></image>
    </view>
  </view>
</template>

<script>
const audioCtxFc = require('./audioCtxFactory');
const playStatus = require('./playStatus');

export default {
  data() {
    return {
      playStatus,
      curStatus: playStatus.STOP,
      time: '0s',
      opcity: 1,
      __comps__: {
        audioCtx: null
      },
      style: '',

      showAnimation: false,

      voiceMsgMyLeft: require('../../common/left.gif'),
      voiceMsgLeft: require('../../common/left.png'),

      voiceMsgMyRight: require('../../common/right.gif'),
      voiceMsgRight: require('../../common/right.png')
    };
  },

  components: {},
  props: {
    // imId
    imId: {
      type: String,
      default: '',
      required: true
    },
    msg: {
      type: Object,
      val: {}
    },
    mid: {
      ype: String,
      val: ''
    },
    direction: {
      type: String,
      val: ''
    }
  },
  obeyMuteSwitch: false,
  autoplay: true,

  created() {},

  beforeMount() {
    // this.time = this.msg.payloadJson?this.msg.payloadJson.bodies[0].length+'s':this.msg.length + "s"
    this.time = `${this.msg.length}s`;
  },

  destroyed() {
    // let audioCtx = this.$data.__comps__.audioCtx = audioCtxFc.getCtx(this.msg.payloadJson?this.msg.payloadJson.ext.mid:this.mid);
    const audioCtx = (this.$data.__comps__.audioCtx = audioCtxFc.getCtx(
      this.mid
    ));
    this.audioPause(audioCtx);
    this.delEvent();
  },

  mounted() {
    const self = this;
    const curl = '';

    // let audioCtx = this.$data.__comps__.audioCtx = audioCtxFc.getCtx(this.msg.payloadJson?this.msg.payloadJson.ext.mid:this.mid);
    const audioCtx = (this.$data.__comps__.audioCtx = audioCtxFc.getCtx(
      this.mid
    ));

    audioCtx.autoplay = false;
    audioCtx.loop = false; //

    this.onPlaying = () => {
      this.showAnimation = true;
      this.curStatus = playStatus.PLAYING;
      uni.inter && clearInterval(uni.inter);
    };

    this.onPause = () => {
      this.showAnimation = false;
      // 第二次播放会立即抛出一个异常的 onPause
      if (parseInt(this.time, 10) < 1) {
        return;
      }
      this.curStatus = playStatus.PAUSE;
      this.opcity = 1;
    };

    this.onDone = () => {
      this.showAnimation = false;
      this.curStatus = playStatus.STOP;
      this.opcity = 1;
      clearInterval(uni.inter);
    }; // 多次播放会丢失这个回调

    this.onTimeUpdate = () => {
      this.time = `${audioCtx.currentTime >> 0}'`;
    };

    this.onWait = () => {
      console.log('下载中...');
    };

    this.addEvent();
  },

  methods: {
    audioPlay() {
      uni.inter && clearInterval(uni.inter);
      const audioCtx = this.$data.__comps__.audioCtx;
      let curl = '';
      uni.downloadFile({
        // url: this.msg.payloadJson?this.msg.payloadJson.bodies[0].url:this.msg.content,
        url: this.msg.data,
        header: {
          'X-Requested-With': 'XMLHttpRequest',
          Accept: 'audio/mp3',
          Authorization: `Bearer ${
            this.$hxim.get(this.imId).conn.context.accessToken
          }`
        },

        success(res) {
          curl = res.tempFilePath;
          console.log('音频本地', audioCtx);

          audioCtx.src = curl;
          audioCtx.play();
        },

        fail(e) {
          console.log('downloadFile failed', e);
          uni.showToast({
            title: '下载失败',
            duration: 1000
          });
        }
      });
    },

    audioPause(auCtx) {
      // let audioCtx = this.$data.__comps__.audioCtx = audioCtxFc.getCtx(this.msg.payloadJson?this.msg.payloadJson.ext.mid:this.mid) || auCtx;
      const audioCtx = (this.$data.__comps__.audioCtx =
        audioCtxFc.getCtx(this.mid) || auCtx);
      audioCtx && audioCtx.pause();
    },

    addEvent() {
      const audioCtx = this.$data.__comps__.audioCtx;
      audioCtx.onPlay(this.onPlaying);
      audioCtx.onPause(this.onPause);
      audioCtx.onWaiting(this.onPause);
      audioCtx.onStop(this.onDone);
      audioCtx.onEnded(this.onDone);
      audioCtx.onError(this.onDone);
      audioCtx.onWaiting(this.onWait); // audioCtx.onTimeUpdate(this.onTimeUpdate);
    },

    delEvent() {
      const audioCtx = this.$data.__comps__.audioCtx;
      audioCtx.offPlay(this.onPlaying);
      audioCtx.offPause(this.onPause);
      audioCtx.offWaiting(this.onPause);
      audioCtx.offStop(this.onDone);
      audioCtx.offEnded(this.onDone);
      audioCtx.offError(this.onDone);
      audioCtx.offWaiting(this.onWait); // 多次播放会丢失这个回调，所以不用卸载
      // audioCtx.offTimeUpdate(this.onTimeUpdate);
    }
  }
};
</script>

<style scoped lang="scss">
.audio-player {
  position: relative;
  overflow: hidden;
  display: flex;
  transition: opacity 0.5s;
}

.audio-player .controls {
  height: 40rpx;
  align-items: center;
  display: flex;
}

.audio-player .controls image {
  height: 40rpx;
  width: 40rpx;
  margin: 0 8rpx 0 30rpx;
}

.audio-player .time {
  font-size: 34rpx;
  line-height: 40rpx;
  flex: 1;
  text-align: left;
}
.audio-left {
  transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
}
</style>
